package util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * Created by CHENCO7 on 7/27/2017.
 */
public class Base64Util {
    /**
     * @param path "d:/test.jpg"
     * @return base64 字符串
     */
    public static String GetImageStr(String path)
    {
        InputStream in = null;
        byte[] data = null;
        try
        {
            in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return "data:img/jpg;base64," + encoder.encode(data);
    }

    /**
     *
     * @param imageString ""
     * @param outputPath "image.png"
     * @param pictureType "png"
     */
    public static void parseBase64(String imageString, String outputPath, String pictureType){
        try {
            String[] split = imageString.split(",");
            BufferedImage image = null;
            byte[] imageByte;

            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(split[1]);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();

            File out = new File(outputPath);
            ImageIO.write(image, pictureType, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println(GetImageStr("d:/test.jpg"));
//        parseBase64(GetImageStr("d:/test.jpg"), "test.jpg", "png");
    }
}
